package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.tool.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;

    @Autowired
    RedisTemplate redisTemplate;

    /**
     * 发送手机短信验证码
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpServletRequest request) {
        //获取手机号
        String phone = user.getPhone();
        //获取验证码
        String code = ValidateCodeUtils.generateValidateCode4String(4);

        log.info(code);
        //request.getSession().setAttribute("code", code);
        //reids里添加验证码
        redisTemplate.opsForValue().set("code_" + phone, code, 2, TimeUnit.MINUTES);
        return R.success("手机验证码短信发送成功");
    }

    @PostMapping("login")
    public R<User> login(@RequestBody Map<String, String> map, HttpServletRequest request) {
        String code = map.get("code");
        String phone = map.get("phone");
        //String code1 = (String) request.getSession().getAttribute("code");
        //获取redis验证码
        String code1 = (String) redisTemplate.opsForValue().get("code_" + phone);
        if (!code.equals(code1)) {
            return R.error("验证码输入错误");
        }

        LambdaQueryWrapper<User> queryWrapper = Wrappers.lambdaQuery(User.class)
                .eq(User::getPhone, phone);
        User user = userService.getOne(queryWrapper);
        if (user == null) {
            user = new User();
            user.setPhone(phone);
            userService.save(user);
        }
        //登录成功销毁验证码
        redisTemplate.delete("code_" + phone);
        request.getSession().setAttribute("user", user.getId());
        return R.success(user);
    }
}
